package works

import (
	"log"
	"net/http"

	"poetry/database"
	"poetry/model"
	"github.com/gin-gonic/gin"
)

func GetWorksList(c *gin.Context) {
	name := c.Query("name")
	if name == "" {
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"msg": "作者不能为空",
		})
	} else {
		var poetries []model.Poetry
		database.DB.Model(&model.Poetry{}).Where("name = ?", name).Find(&poetries)

		var result = make([]model.PoetrySerializer, len(poetries))
		for index, poetry := range poetries {
			result[index] = poetry.Serializer()
		}

		c.JSON(http.StatusOK, gin.H{
			"code":    0,
			"msg": "数据查询中...",
			"data": gin.H{
				"list": result,
				"Request": c.Request.Body,
			},
		})
	}
}

func GetDeleteWorks(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"msg": "ID不能为空",
		})
	} else {
		if err := database.DB.Where("id = ?", id).Delete(&model.Poetry{}).Error; err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code":    -1,
				"msg": "删除失败",
			})
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code":    0,
				"msg": "删除成功",
			})
		}
	}
}

type CreateForm struct {
	Name	  string `json:"name" binding:"required"`
	Title	  string `json:"title" binding:"required"`
	Dynasty	string `json:"dynasty" binding:"required"`
	Content	string `json:"content" binding:"required"`
	Tags	  string `json:"tags" binding:"required"`
}

func CreateWorks(c *gin.Context) {
	var createForm CreateForm
	if err := c.ShouldBindJSON(&createForm); err != nil {
		log.Println(createForm)
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"msg": "请输入正确的参数",
		})
	} else {
		var poetry model.Poetry
		if err := database.DB.Model(&model.Poetry{}).Where("title = ?", createForm.Title).First(&poetry).Error; err != nil {
			poetry.Name = createForm.Name
			poetry.Title = createForm.Title
			poetry.Dynasty = createForm.Dynasty
			poetry.Content = createForm.Content
			poetry.Tags = createForm.Tags
			database.DB.Create(&poetry)
			c.JSON(http.StatusOK, gin.H{
				"code":    0,
				"msg":  "添加成功",
				"data": poetry.Serializer(),
			})
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code":    -1,
				"msg":  "诗词已存在，请勿重复添加",
			})
		}
	}
}
